<?PHP
namespace common\components;

use Yii;
use yii\base\Component;
use yii\web\Response;

/**
 * 成功
 * Yii::$app->message->success($data = []);
 *
 * 前端不参与errno判断，仅显示错误信息
 * Yii::$app->message->fail('xxx错误', $data = [])
 *
 * 前端会参与errno判断的错误, 例如名称重复
 * 数组字典没有找到对应的message会抛出异常
 * Yii::$app->message->error($errno, $params = [], $data = [])
 */
class Message extends Component
{
    // 成功
    const OK = 0;
    const MESSAGE_OK = '操作成功';

    // 自定义错误消息
    const FAILED = 1; 
    const MESSAGE_FAILED = '操作失败'; 

    const PARAM_ERRNO = 'e';
    const PARAM_MESSAGE = 'm';
    const PARAM_DATA = 'd';

    // 数据字典的类
    public $dict = null;

    protected function getMessage($errno, $params = [])
    {
        if (!$this->dict || !class_exists($this->dict)) {
            throw new \Exception('数据字典不存在');
        }
        if (!is_array($params)) {
            $params = [$params];
        }
        return call_user_func([$this->dict, 'get'], $errno, $params);
    }

    public function error($errno, $params= [], $data = [])
    {
        $message = $this->getMessage($errno, $params);
        $this->show($errno, $message, $data);
    }

    public function fail($message = '', $data = [])
    {
        if (!$message) {
            $message = self::MESSAGE_FAILED;
        }
        $this->show(self::FAILED, $message, $data);
    }

    public function success($data = [])
    {
        $this->show(self::OK, self::MESSAGE_OK, $data);
    }

    public function show($errno, $message = '', $data = [])
    {
        $json = [
            self::PARAM_ERRNO => $errno,
            self::PARAM_MESSAGE => $message,
            self::PARAM_DATA => $data,
        ];
        $resp = Yii::$app->response;

        if ($resp->format == Response::FORMAT_JSONP) {
            $resp->data['data'] = $json;
        } else {
            $resp->format = Response::FORMAT_JSON;
            $resp->data = $json;
        }
        $resp->send();
        Yii::$app->end();
    }
}
?>
